<template>
  <div>
    <div style="margin: 10px 0">
      <el-input
        style="width: 200px"
        placeholder="请输入名称"
        suffix-icon="el-icon-search"
        v-model="name"
      ></el-input>
      <el-button class="ml-5" type="primary" @click="load()">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button
        type="primary"
        @click="handleAdd"
        >新增 <i class="el-icon-circle-plus-outline"></i
      ></el-button>
      <el-popconfirm
        class="ml-5"
        confirm-button-text="确定"
        cancel-button-text="我再想想"
        icon="el-icon-info"
        icon-color="red"
        title="您确定批量删除这些数据吗？"
        @confirm="delBatch"
      >
        <el-button type="danger" slot="reference"
          >批量删除 <i class="el-icon-remove-outline"></i
        ></el-button>
      </el-popconfirm>
    </div>

    <el-table
      :data="tableData"
      border
      stripe
      :header-cell-class-name="'headerBg'"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="siteName" label="站点名称"></el-table-column>
      <el-table-column prop="siteAdmin" label="站点管理员"></el-table-column>
      <el-table-column prop="siteLocation" label="站点位置"></el-table-column>
      <el-table-column prop="avatarUrl" label="站点图片">
        <template class="block" v-slot:default="scope">
          <el-popover placement="left" trigger="click" width="300">
            <img :src="scope.row.avatarUrl" width="100%" />
            <img
              slot="reference"
              :src="scope.row.avatarUrl"
              :alt="scope.row.avatarUrl"
              style="max-height: 70px; max-width: 70px; padding: 5px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="selectPowerBank(scope.row.id)"
            >查看管理的充电宝</el-button
          >
          <el-button
            type="success"
            @click="handleEdit(scope.row)"
            >编辑 <i class="el-icon-edit"></i
          ></el-button>
          <el-popconfirm
            class="ml-5"
            confirm-button-text="确定"
            cancel-button-text="我再想想"
            icon="el-icon-info"
            icon-color="red"
            title="您确定删除吗？"
            @confirm="del(scope.row.id)"
          >
            <el-button
              type="danger"
              slot="reference"
              >删除 <i class="el-icon-remove-outline"></i
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog title="站点信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="90px" size="small">
        <el-form-item label="站点名称">
          <el-input v-model="form.siteName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="站点管理员">
          <el-input v-model="form.siteAdmin" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="站点位置">
          <el-input v-model="form.siteLocation" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            v-model="form.avatarUrl"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="handlerChange"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="充电宝列表" :visible.sync="dialogListVisible">
      <el-table :data="powerBankList">
        <el-table-column
          property="brand"
          label="品牌"
          width="200"
        ></el-table-column>
        <el-table-column property="numbers" label="数量"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Site",
  data() {
    return {
      form: {},
      tableData: [],
      name: "",
      powerBankList: [],
      dialogListVisible: false,
      multipleSelection: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      user: localStorage.getItem("user")
        ? JSON.parse(localStorage.getItem("user"))
        : {},
      avatarUrl: "",
      primaryKey: ""
    };
  },
  created() {
    this.load();
  },
  methods: {
    //图片上传成功
    handleAvatarSuccess(res, file) {
      this.avatarUrl = res;
      this.form.avatarUrl = res
    },
    //上传站点图片
    handlerChange(param) {
      let formData = new FormData();
      formData.append("file", param.file);
      formData.append("id", this.primaryKey);
      this.request.post("/site/upload", formData).then((res) => {
        this.avatarUrl = res;
        this.form.avatarUrl = this.avatarUrl;
      });
    },
    //上传图片前进行校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      return isJPG && isLt2M;
    },
    selectPowerBank(id) {
      this.request
        .get("/powerBank/getList", {
          params: {
            siteId: id,
          },
        })
        .then((res) => {
          this.powerBankList = res.records;
          this.dialogListVisible = true;
        });
    },
    load() {
      this.request
        .get("/site/getList", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            userId: this.user.id,
            role: this.user.role,
            name: this.name,
          },
        })
        .then((res) => {
          this.tableData = res.records;
          this.total = res.total;
        });
    },
    changeEnable(row) {
      this.request.post("/course/update", row).then((res) => {
        if (res.code === "200") {
          this.$message.success("操作成功");
        }
      });
    },
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {};
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      console.log(this.form);
      this.primaryKey = this.form.id;
      this.dialogFormVisible = true;
    },
    del(id) {
      this.request.post("site/delete/" + id).then((res) => {
        if (res.code === "200") {
          this.$message.success("删除成功");
          this.load();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
    },
    delBatch() {
      let ids = this.multipleSelection.map((v) => v.id); // [{}, {}, {}] => [1,2,3]
      console.log(ids);
      this.request.post("/site/del/batch", ids).then((res) => {
        if (res.code === "200") {
          this.$message.success("批量删除成功");
          this.load();
        } else {
          this.$message.error("批量删除失败");
        }
      });
    },
    save() {
      this.form.userId = this.user.id;
      this.form.avatarUrl = this.avatarUrl;
      this.request.post("/site/saveOrUpdate", this.form).then((res) => {
        if (res.code === "200") {
          this.$message.success("保存成功");
          this.dialogFormVisible = false;
          this.load();
        } else {
          this.$message.error("保存失败");
        }
      });
    },
    reset() {
      this.name = "";
      this.load();
    },
    handleSizeChange(pageSize) {
      console.log(pageSize);
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum);
      this.pageNum = pageNum;
      this.load();
    }
  },
};
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
